import { isArray } from 'lodash-es'
import { useEffect } from 'react'

import { getCitiesTreeApi } from '@/api/pcs/cities'
import { createCompanionCompanyApi, updateCompanionCompanyApi } from '@/api/pcs/pcsCompanionCompany'
import { hospitalListApi } from '@/api/pcs/pcsHospital'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { requestWithTry } from '@/utils/request'

const EditModal = ({ row = {} }) => {
  const [form] = AekForm.useForm()
  const { id } = row

  useEffect(() => {
    if (!row.id) return
    form.setFieldsValue({
      ...row,
    })
  }, [row.id])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'name',
      label: '公司名称',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
    },
    {
      field: 'serviceProvidingCityId',
      label: '服务城市',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekTreeSelect',
        props: {
          api: getCitiesTreeApi,
        },
      },
    },
    {
      field: 'serviceProvidingHospitalId',
      label: '服务医院',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekSelect',
        props: {
          api: hospitalListApi,
        },
      },
    },
    {
      field: 'remark',
      label: '备注',
      component: { name: 'AekTextArea' },
    },
    {
      field: 'fileUrl',
      label: '付款码',
      component: { name: 'AekUpload', props: { fileType: 'img', listType: 'picture-card' } },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      id,
      ...values,
      fileUrl: isArray(values.fileUrl) ? values.fileUrl.map(({ url }) => url).join(',') : '',
    }
    await requestWithTry(id ? updateCompanionCompanyApi : createCompanionCompanyApi, params)
  }
  return (
    <AekModal title={id ? '编辑' : '新增'} width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

EditModal.PromiseThen = PromiseThen

export default EditModal
